package com.stx.jeepay.manager.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stx.jeepay.core.aop.MethodLog;
import com.stx.jeepay.core.entity.MchPayPassageEntity;
import com.stx.jeepay.core.entity.PayOrderEntity;
import com.stx.jeepay.core.entity.PayWayEntity;
import com.stx.jeepay.core.enums.ApiCodeEnum;
import com.stx.jeepay.core.expection.BizException;
import com.stx.jeepay.core.model.ApiPageRes;
import com.stx.jeepay.core.model.ApiRes;
import com.stx.jeepay.core.service.MchPayPassageService;
import com.stx.jeepay.core.service.PayOrderService;
import com.stx.jeepay.core.service.PayWayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@Api(tags = "支付方式配置")
@RestController
@RequestMapping("api/payWays")
public class PayWayController extends CommonCtrl {

    @Autowired
    private PayWayService payWayService;
    @Autowired
    private MchPayPassageService mchPayPassageService;
    @Autowired
    private PayOrderService payOrderService;

    @ApiOperation("支付方式--列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "pageNumber", value = "分页页码", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "分页条数（-1时查全部数据）", dataType = "int", defaultValue = "20"),
            @ApiImplicitParam(name = "wayCode", value = "支付方式代码"),
            @ApiImplicitParam(name = "wayName", value = "支付方式名称")
    })
    @PreAuthorize("hasAnyAuthority('ENT_PC_WAY_LIST', 'ENT_PAY_ORDER_SEARCH_PAY_WAY')")
    @GetMapping
    public ApiPageRes<PayWayEntity> list() {
        PayWayEntity queryObject = getObject(PayWayEntity.class);

        LambdaQueryWrapper<PayWayEntity> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotEmpty(queryObject.getWayCode())) {
            queryWrapper.like(PayWayEntity::getWayCode, queryObject.getWayCode());
        }

        if (StringUtils.isNotEmpty(queryObject.getWayName())) {
            queryWrapper.like(PayWayEntity::getWayName, queryObject.getWayName());
        }
        queryWrapper.orderByDesc(PayWayEntity::getWayCode);

        IPage<PayWayEntity> pages = payWayService.page(getIPage(true), queryWrapper);

        return ApiPageRes.pages(pages);
    }

    @ApiOperation("支付方式--详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "wayCode", value = "支付方式代码", required = true)
    })
    @PreAuthorize("hasAnyAuthority('ENT_PC_WAY_VIEW', 'ENT_PC_WAY_EDIT')")
    @GetMapping("/{wayCode}")
    public ApiRes detail(@PathVariable("wayCode") String wayCode) {
        return ApiRes.ok(payWayService.getById(wayCode));
    }

    @ApiOperation("支付方式--新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "wayCode", value = "支付方式代码", required = true),
            @ApiImplicitParam(name = "wayName", value = "支付方式名称", required = true)
    })
    @PreAuthorize("hasAuthority('ENT_PC_WAY_ADD')")
    @MethodLog(remark = "新增支付方式")
    @PostMapping
    public ApiRes add() {
        PayWayEntity payWay = getObject(PayWayEntity.class);
        if (payWayService.count(new LambdaQueryWrapper<PayWayEntity>().eq(PayWayEntity::getWayCode, payWay.getWayCode())) > 0) {
            throw new BizException("支付方式代码已存在");
        }
        payWay.setWayCode(payWay.getWayCode().toUpperCase());

        boolean result = payWayService.save(payWay);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
        }
        return ApiRes.ok();
    }

    @ApiOperation("支付方式--更新")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "wayCode", value = "支付方式代码", required = true),
            @ApiImplicitParam(name = "wayName", value = "支付方式名称", required = true)
    })
    @PreAuthorize("hasAuthority('ENT_PC_WAY_EDIT')")
    @MethodLog(remark = "更新支付方式")
    @PutMapping("/{wayCode}")
    public ApiRes update(@PathVariable("wayCode") String wayCode) {
        PayWayEntity payWay = getObject(PayWayEntity.class);
        payWay.setWayCode(wayCode);
        boolean result = payWayService.updateById(payWay);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
        }
        return ApiRes.ok();
    }

    @ApiOperation("支付方式--删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "wayCode", value = "支付方式代码", required = true)
    })
    @PreAuthorize("hasAuthority('ENT_PC_WAY_DEL')")
    @MethodLog(remark = "删除支付方式")
    @DeleteMapping("/{wayCode}")
    public ApiRes delete(@PathVariable("wayCode") String wayCode) {
        if (mchPayPassageService.count(new LambdaQueryWrapper<MchPayPassageEntity>().eq(MchPayPassageEntity::getWayCode, wayCode)) > 0
                || payOrderService.count(new LambdaQueryWrapper<PayOrderEntity>().eq(PayOrderEntity::getWayCode, wayCode)) > 0) {
            throw new BizException("该支付方式已有商户配置通道或已发生交易，无法删除！");
        }

        boolean result = payWayService.removeById(wayCode);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_DELETE);
        }
        return ApiRes.ok();
    }
}
